// index.js
import {
  API,
  getUrl
} from '../../utils/api'
// 获取应用实例
const app = getApp()

Page({
  data: {
    phoneNumber: '',
    openid: '',
    sessionKey: '',
    statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
    schoolInfo: {},
    isShowDialog: false
  },
  onLoad() {
    // 登录并获取用户信息
    wx.login({
      success: (res) => {
        if (res.code) {
          wx.request({
            url: getUrl(API.OAUTH),
            data: {
              code: res.code
            },
            success: (res) => {
              let userInfo = res.data.data;
              this.setData({
                phoneNumber: userInfo.phoneNumber || '',
                openid: userInfo.openid,
                sessionKey: userInfo.session_key
              })
            }
          })
        }
      }
    })
  },
  navigateToAppointment() {
    if (this.data.schoolInfo.schoolName) {
      wx.navigateTo({
        url: '../appointment/index',
        success: (res) => {
          res.eventChannel.emit('sendData', this.data)
        }
      })
    } else {
      this.setData({
        isShowDialog: true
      })
    }

  },
  navigateToOrder() {
    wx.navigateTo({
      url: '../order/index',
      success: (res) => {
        res.eventChannel.emit('sendData', {openid:this.data.openid})
      }
    })
  },
  navigateToSchool() {
    wx.navigateTo({
      url: '../searchSchool/index',
      events: {
        searchSchoolEvent: (data) => {
          this.setData({
            schoolInfo: data.data
          })
        }
      }
    })
  },
  getPhoneNumber(e) {
    if (e.detail.encryptedData) {
      wx.request({
        url: getUrl(API.PHONE_NUMBER),
        method: "POST",
        data: {
          openid: this.data.openid,
          session_key: this.data.sessionKey,
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData
        },
        success: (res) => {
          let phone = res.data.data.phoneNumber;
          if (phone) {
            this.setData({
              phoneNumber: phone
            })
            let key = e.currentTarget.dataset.key;
            if (key == 'order') {
              this.navigateToOrder();
            } else if (key == 'school') {
              this.navigateToSchool();
            } else {
              this.navigateToAppointment();
            }

          }
        }
      })
    }
  },
  closeDialog() {
    this.setData({
      isShowDialog: false
    })
  }
})